package net.sppan.base.controller.mg;

import net.sppan.base.controller.BaseController;
import net.sppan.base.entity.mgEntity.MgUser;
import net.sppan.base.entity.mgEntity.MgUserCode;
import net.sppan.base.enumType.BuyCarType;
import net.sppan.base.enumType.CodeStatusTYpe;
import net.sppan.base.enumType.MgUserRegisterType;
import net.sppan.base.service.IMgUserCodeService;
import net.sppan.base.service.IMgUserService;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
public class MgUserController extends BaseController{

	@Autowired
	private IMgUserService userService;

	@Autowired
	private IMgUserCodeService userCodeService;

	private Logger logger = LoggerFactory.getLogger(getClass());

	final SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	/**
	 *下载excel模板
	 * @param response
	 */
	@RequestMapping(value = "/mg/downLoadExcelHexiao",method = {RequestMethod.POST,RequestMethod.GET})
	@ResponseBody
	public void downLoadExcelHexiao(HttpServletResponse response,String startTime,String endTime){
		List<MgUserCode>  classmateList = exportExcelHexiao(startTime,endTime);

		HSSFWorkbook workbook = new HSSFWorkbook();
		HSSFSheet sheet = workbook.createSheet("核销信息表");
		createTitleHexiao(sheet);
		//拼装blobName
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
		String fileName = "mgUserCodeInfo-" + dateFormat.format(new Date()) + ".xls";
		//新增数据行，并且设置单元格数据
		int rowNum = 1;
		for (MgUserCode classmate : classmateList) {
			HSSFRow row = sheet.createRow(rowNum);
			row.createCell(0).setCellValue(dateFormat1.format(new Date(classmate.getCreatedTime())));
			row.createCell(1).setCellValue(classmate.getUserName());
			row.createCell(2).setCellValue(classmate.getTelephone());
			row.createCell(3).setCellValue(classmate.getCode());
			rowNum++;
		}

		response.setContentType("application/octet-stream");
		response.setHeader("Content-disposition", "attachment;filename=" + fileName);
		try {
			response.flushBuffer();
			workbook.write(response.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 *下载excel模板
	 * @param response
	 */
	@RequestMapping(value = "/mg/downLoadExcel",method = {RequestMethod.POST,RequestMethod.GET})
	@ResponseBody
	public void downLoadExcel(HttpServletResponse response,String startTime,String endTime){
		List<MgUser>  classmateList = exportExcel(startTime, endTime);

		HSSFWorkbook workbook = new HSSFWorkbook();
		HSSFSheet sheet = workbook.createSheet("留资信息表");
		createTitle(sheet);
		//拼装blobName
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
		String fileName = "mgUserInfo-" + dateFormat.format(new Date()) + ".xls";
		//新增数据行，并且设置单元格数据
		int rowNum = 1;
		for (MgUser classmate : classmateList) {
			HSSFRow row = sheet.createRow(rowNum);
			row.createCell(0).setCellValue(MgUserRegisterType.getDescByName(classmate.getSourceType()));
			row.createCell(1).setCellValue(dateFormat1.format(new Date(classmate.getCreateadTime())));
			row.createCell(2).setCellValue(classmate.getUserName());
			row.createCell(3).setCellValue(classmate.getTelephone());
			row.createCell(4).setCellValue(BuyCarType.getDescByName(classmate.getBuyCarTime()));
			row.createCell(5).setCellValue(classmate.getInterestCarType());
			rowNum++;
		}

		response.setContentType("application/octet-stream");
		response.setHeader("Content-disposition", "attachment;filename=" + fileName);
		try {
			response.flushBuffer();
			workbook.write(response.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/***
	 * 创建表头
	 * @param sheet
	 */
	private void createTitle(HSSFSheet sheet){
		HSSFRow row = sheet.createRow(0);
		//设置列宽，setColumnWidth的第二个参数要乘以256，这个参数的单位是1/256个字符宽度
		sheet.setColumnWidth(0, 10*256);
		sheet.setColumnWidth(1, 30*256);
		sheet.setColumnWidth(2, 30*256);
		sheet.setColumnWidth(3, 30*256);
		sheet.setColumnWidth(4, 30*256);
		sheet.setColumnWidth(5, 30*256);
		HSSFCell cell;
		cell = row.createCell(0);
		cell.setCellValue("渠道");

		cell = row.createCell(1);
		cell.setCellValue("留资日期");

		cell = row.createCell(2);
		cell.setCellValue("留资人");

		cell = row.createCell(3);
		cell.setCellValue("留资电话");

		cell = row.createCell(4);
		cell.setCellValue("购车意向");

		cell = row.createCell(5);
		cell.setCellValue("意向车型");
	}
	/***
	 * 创建表头
	 * @param sheet
	 */
	private void createTitleHexiao(HSSFSheet sheet){
		HSSFRow row = sheet.createRow(0);
		//设置列宽，setColumnWidth的第二个参数要乘以256，这个参数的单位是1/256个字符宽度
		sheet.setColumnWidth(0, 30*256);
		sheet.setColumnWidth(1, 30 * 256);
		sheet.setColumnWidth(2, 30*256);
		sheet.setColumnWidth(3, 30 * 256);
		HSSFCell cell;
		cell = row.createCell(0);
		cell.setCellValue("核销时间");

		cell = row.createCell(1);
		cell.setCellValue("被核销人");

		cell = row.createCell(2);
		cell.setCellValue("被核销电话");

		cell = row.createCell(3);
		cell.setCellValue("券码");
	}
	private  List<MgUser>  exportExcel(final String startTime,final String endTime){

		Sort sort = new Sort(new Sort.Order(Sort.Direction.DESC,"createadTime"));

		final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

		Specification<MgUser> specification = new Specification() {
			@Override
			public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) {
				Predicate predicate = criteriaBuilder.conjunction();

				if(!Objects.equals(null,startTime)){
					long start = 0;
					try {
						start = simpleDateFormat.parse(startTime).getTime();
					} catch (ParseException e) {
						e.printStackTrace();
					}
					predicate.getExpressions().add(criteriaBuilder.greaterThan(root.get("createadTime").as(Long.class),start));
				}
				if(!Objects.equals(null,endTime)){
					long end = 0;
					try {
						end = simpleDateFormat.parse(endTime).getTime();
					} catch (ParseException e) {
						e.printStackTrace();
					}
					predicate.getExpressions().add(criteriaBuilder.lessThan(root.get("createadTime").as(Long.class),end));
				}
				return predicate;
			}
		};
		List<MgUser> list= userService.findList(specification,sort);
		return list;
	}

	private  List<MgUserCode>  exportExcelHexiao(final String startTime,final String endTime){

		Sort sort = new Sort(new Sort.Order(Sort.Direction.DESC,"createdTime"));

		final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

		Specification<MgUserCode> specification = new Specification() {
			@Override
			public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) {
				Predicate predicate = criteriaBuilder.conjunction();

				if(!Objects.equals(null,startTime)){
					long start = 0;
					try {
						start = simpleDateFormat.parse(startTime).getTime();
					} catch (ParseException e) {
						e.printStackTrace();
					}
					predicate.getExpressions().add(criteriaBuilder.greaterThan(root.get("createdTime").as(Long.class),start));
				}
				if(!Objects.equals(null,endTime)){
					long end = 0;
					try {
						end = simpleDateFormat.parse(endTime).getTime();
					} catch (ParseException e) {
						logger.error("query  failed!");
					}
					predicate.getExpressions().add(criteriaBuilder.lessThan(root.get("createadTime").as(Long.class),end));
				}
				predicate.getExpressions().add(criteriaBuilder.equal(root.get("codeStatus"), CodeStatusTYpe.YiHeXiao.name()));
				return predicate;
			}
		};
		List<MgUserCode> list= userCodeService.findList(specification,sort);
		return list;
	}

	/**
	 * 留资信息
	 * @return
	 */
	@RequestMapping(value = {"admin/mgUser/index" })
	public String index() {
		return "admin/mgUser/index";
	}

	/**
	 * 核销页面
	 * @return
	 */
	@RequestMapping(value = {"admin/mgUserCodeHexiao/index"})
	public String indexHexiao() {
		return "admin/mgUserCode/hexiao";
	}

	/**
	 * 核销信息
	 * @return
	 */
	@RequestMapping(value = {"admin/mgUserCode/index" })
	public String indexUserCode() {
		return "admin/mgUserCode/index";
	}

	@RequestMapping(value = { "mg/mgUserCode/list" },produces = "application/json;charset=utf-8")
	@ResponseBody
	public Page<MgUserCode> mgUserCodeList(final String startTime, final String endTime, HttpServletRequest request, HttpServletResponse response) {
		final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

		Specification<MgUserCode> specification = new Specification() {
			@Override
			public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) {
				Predicate predicate = criteriaBuilder.conjunction();

				if(!Objects.equals(null,startTime)){
					long start = 0;
					try {
						start = simpleDateFormat.parse(startTime).getTime();
					} catch (ParseException e) {
						e.printStackTrace();
					}
					predicate.getExpressions().add(criteriaBuilder.greaterThan(root.get("createdTime").as(Long.class),start));
				}
				if(!Objects.equals(null,endTime)){
					long end = 0;
					try {
						end = simpleDateFormat.parse(endTime).getTime();
					} catch (ParseException e) {
						e.printStackTrace();
					}
					predicate.getExpressions().add(criteriaBuilder.lessThan(root.get("createdTime").as(Long.class),end));
				}
				return predicate;
			}
		};

		Page<MgUserCode> page = userCodeService.findAll(specification, getPageRequest());

		response.setCharacterEncoding("utf-8");
		return page;
	}

	@RequestMapping(value = { "mg/list" })
	@ResponseBody
	public Page<MgUser> list(final String startTime, final String endTime, HttpServletRequest request, HttpServletResponse response) {
		final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

			Specification<MgUser> specification = new Specification() {
			@Override
			public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) {
				Predicate predicate = criteriaBuilder.conjunction();

				if(!Objects.equals(null,startTime)){
					long start = 0;
					try {
						start = simpleDateFormat.parse(startTime).getTime();
					} catch (ParseException e) {
						e.printStackTrace();
					}
					predicate.getExpressions().add(criteriaBuilder.greaterThan(root.get("createadTime").as(Long.class),start));
				}
				if(!Objects.equals(null,endTime)){
					long end = 0;
					try {
						end = simpleDateFormat.parse(endTime).getTime();
					} catch (ParseException e) {
						e.printStackTrace();
					}
					predicate.getExpressions().add(criteriaBuilder.lessThan(root.get("createadTime").as(Long.class),end));
				}
				return predicate;
			}
		};

			Page<MgUser> page = userService.findAll(specification, getPageRequest());
			return page;
	}
}
